package com.showtao.front.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.showtao.common.dto.ResultDto;
import com.showtao.common.dto.ResultDtoFactory;
import com.showtao.common.dto.widget.DataTablesResponseDto;
import com.showtao.common.util.JsonUtil;
import com.showtao.common.validation.ValidateException;
import com.showtao.front.domain.MobileOrder;
import com.showtao.front.domain.MobileUser;
import com.showtao.front.domain.Order;
import com.showtao.front.dto.upstream.OrderQueryRequestDto;
import com.showtao.front.dto.upstream.SMSSendingDto;
import com.showtao.front.dto.upstream.SMSValidatingDto;
import com.showtao.front.service.OrderService;

@Controller
public class OrderController {

    @Autowired
    private OrderService orderService;
    
    @RequestMapping(value = "/order/send_sms", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto doSendSMS(@Valid @RequestBody SMSSendingDto dto,
            BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new ValidateException(result);
        }
        orderService.sendValidationCode(dto.getMobile());
        return ResultDtoFactory.toAck("短信验证码发送成功");
    }
    
    @RequestMapping(value = "/order/validate_sms", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto doValidateSMS(@Valid @RequestBody SMSValidatingDto dto,
            BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new ValidateException(result);
        }
        orderService.validateCode(dto.getMobile(), dto.getCode());
        return ResultDtoFactory.toAck("短信验证成功");
    }
    
    @RequestMapping(value = "/orders", method = RequestMethod.POST)
    @ResponseBody
    public DataTablesResponseDto<Order> doSearchOrders(
            @Valid @RequestBody OrderQueryRequestDto requestDto,
            BindingResult result, HttpSession session) throws Exception {
        if (result.hasErrors()) {
            throw new ValidateException(result);
        }
        Pageable pageable = requestDto.toPagable();
        Page<Order> page = orderService.findOrdersByMobile(requestDto.getMobile(), pageable);
        DataTablesResponseDto<Order> responseDto = new DataTablesResponseDto<Order>();
        return responseDto.populateFromPage(page, requestDto.getDraw());
    }
    
    //mobile functions
    @RequestMapping(value = "/mobile/order_send_sms", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto doOrderQuerySendSMS(String mobile) throws Exception {
    	try{
    		orderService.sendValidationCode(mobile);
    	}catch(Exception ex){
    		return ResultDtoFactory.toAck("errorMsg",ex.getMessage());
    	}
        
        return ResultDtoFactory.toAck("短信验证码发送成功");
    }
    
    @RequestMapping(value = "/mobile/find-order")
    public String toOrderQuery(Model model){
        return "order/mobile_find_order";
    }
    
    @RequestMapping(value = "/mobile/find-order/orderList")
    public String orderQuery(Model model, String mobile, String code){
    	try{
    		model.addAttribute("mobile", mobile);
    		orderService.validateCode(mobile, code);
    		model.addAttribute("orders", orderService.findByReceiverPhoneAndOrderDate(mobile, null, null));
    	}catch(Exception ex){
    		model.addAttribute("errorMsg", ex.getMessage());
    	}
    	return "order/foundOrders";
    }
    
    @RequestMapping(value = "/mobile/myOrders")
    public String recentOrders(HttpSession session, Model model){
    	try{
    		MobileUser mobileUser=(MobileUser)session.getAttribute("mobileUser");
    		model.addAttribute("gotoURL", "mobile/myOrders");
    		if(mobileUser==null){
    			return "mobile_login";
    		}
    		String mobile = mobileUser.getMobile();
    		Calendar c = Calendar.getInstance();
    		Date endDate = c.getTime();
    		c.add(Calendar.DAY_OF_MONTH, -10);
    		c.set(Calendar.HOUR_OF_DAY, 0);
    		c.set(Calendar.MINUTE, 0);
    		c.set(Calendar.SECOND, 0);
    		c.set(Calendar.MILLISECOND, 0);
    		Date startDate = c.getTime();
    		List<MobileOrder> orders = orderService.findMobileOrderByMobileAndCreatedDate(mobile, startDate, endDate);
    		model.addAttribute("orders", orders);
    		model.addAttribute("ordersJson", JsonUtil.toJSon(orders));
    	}catch(Exception ex){
    		model.addAttribute("errorMsg", "查询订单异常！");
    	}
    	return "order/orders";
    }
    
    @RequestMapping(value = "/mobile/findOrders")
    @ResponseBody
    public ResultDto findOrders(HttpSession session, String startDate, String endDate){
    	MobileUser mobileUser=(MobileUser)session.getAttribute("mobileUser");
		if(mobileUser==null){
			return ResultDtoFactory.toAck("errorMsg", "会话过期");
		}
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	Date sDate=null;
    	Date eDate=null;
    	try {
    		if((startDate==null  || startDate.length()==0)&& (endDate==null || endDate.length()==0)){
    			eDate=new Date();
    			Calendar c = Calendar.getInstance();
	    		c.add(Calendar.DAY_OF_MONTH, -10);
	    		c.set(Calendar.HOUR_OF_DAY, 0);
	    		c.set(Calendar.MINUTE, 0);
	    		c.set(Calendar.SECOND, 0);
	    		c.set(Calendar.MILLISECOND, 0);
	    		sDate=c.getTime();
    		}else{
    			if(startDate != null && startDate.length() > 0){
    				sDate = sdf.parse(startDate);
    	    	}
    			if(endDate != null && endDate.length() > 0){
    				eDate = sdf.parse(endDate);
    	    	}
    		}
    		
    		return ResultDtoFactory.toAck("successMsg", orderService.findMobileOrderByMobileAndCreatedDate(mobileUser.getMobile(), sDate, eDate));
    	} catch (ParseException e) {
			e.printStackTrace();
			return ResultDtoFactory.toAck("errorMsg", "日期转换异常！");
		} catch (Exception e) {
			e.printStackTrace();
			return ResultDtoFactory.toAck("errorMsg", "会话过期");
		}
    }
    
    @RequestMapping(value = "/mobile/selection/orderEntry/{carTypeCode}")
	public String orderEntry(HttpSession session, Model model, @PathVariable("carTypeCode") String carTypeCode) throws UnsupportedEncodingException{
    	MobileUser mobileUser=(MobileUser)session.getAttribute("mobileUser");
    	model.addAttribute("gotoURL", "mobile/selection/orderEntry/"+carTypeCode);
		if(mobileUser==null){
			return "mobile_login";
		}
		carTypeCode = URLDecoder.decode(carTypeCode,"UTF-8");
		model.addAttribute("carTypeCode", carTypeCode);
		return "order/orderEntry";
	}
	
	@RequestMapping(value = "/mobile/submitOrder")
	@ResponseBody
	public ResultDto submitOrder(HttpSession session, String carTypeCode, String vehicleOwnerName, String mobile, String productName, String productColour, String descrn){
		MobileUser mobileUser=(MobileUser)session.getAttribute("mobileUser");
		if(mobileUser==null){
			return ResultDtoFactory.toAck("errorMsg", "会话过期");
		}
		MobileOrder order = new MobileOrder();
		order.setCarTypeCode(carTypeCode);
		order.setDescrn(descrn);
		order.setMobile(mobile);
		order.setVehicleOwnerName(vehicleOwnerName);
		order.setProductName(productName);
		order.setProductColour(productColour);
		order.setCreatedAt(new Date());
		order.setCreatedBy(mobileUser.getMobile());
		orderService.saveMobileOrder(order);
		return ResultDtoFactory.toAck("successMsg", order);
	}
}
